package com.scalar.chiptrack.adaptor.ikanos.amkor;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;

import javax.mail.Message;
import javax.mail.Address;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.BodyPart;
import java.util.Date;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 30 Sep, 2009
 * Time: 11:46:36 PM
 * To change this template use File | Settings | File Templates.
 */
public class ATPPOP3Adaptor extends JobHandler implements AdaptorConstants
{
    private static final String HOST                = "mail.scalarsoft.com";                             

    public static final String ADAPTOR_NAME         = "ATP_WIP";
    private static final String SUBJECT_DAILY_WIP   = "Reports(1)";

    public static final String ATP_WIP_FILE      = "ATP_WIP";
    private static final String FROM_ADDRESS     = "derick.ignacio@conexant.com";


    private Logger m_adaptorLogger      = null;
    private String m_dataOutputDir      = null;
    private String m_username           = null;
    private String m_password           = null;
    private int    m_adaptor_id     = -1;
    /**
     *
     * @throws Exception
     */
    public ATPPOP3Adaptor() throws Exception
    {
        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_AMKOR_PH, WIP_TYPE_ASSEMBLY );

            m_username = vendorAdaptor.getUserId();
            m_password = vendorAdaptor.getPassWord();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory();

            if ( m_dataOutputDir != null )
            {
                if (m_dataOutputDir.endsWith("/") || m_dataOutputDir.endsWith("\\"))
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
               AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
               m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_AMKOR_PH );
               AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading ATP POP3 Adaptor Username, Password details from database, Exception: " + se);
            throw se;
        }
    }

    //Main Method
    public static void main(String[] args) throws Exception
    {
        new ATPPOP3Adaptor().execute();
    }
    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            //Print the header details
            AdaptorUtils.printHeader(VENDOR_NAME_AMKOR_PH , CONSTANT_ADAPTOR);

            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

            // Step 3
            //Retrive All the Messages
            Message[] messages = AdaptorUtils.getAllPOP3InboxMessages( HOST, m_username, m_password);
            // Step 4
            // Retrieve & Saves the latest message
            readLatestMessage( m_adaptor_id, messages, SUBJECT_DAILY_WIP, m_dataOutputDir, FILE_EXTN_XLS, ATP_WIP_FILE );

        }
        catch (Exception e)
        {
            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id);
            System.out.println("Exception while trying to connect and read data from " + HOST +" site: " + e);
            log("Exception while trying to connect and read data from " + HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }
    public void readLatestMessage( int m_adaptor_id, Message[] message, String subject, String outputDir, String fileType, String appendFileName ) throws Exception
    {
        Message wipMessage  = null;
        if ( message == null || message.length == 0 )
        {
            return;
        }
        BodyPart part = null;
        Multipart mp  = null;
        /*To download Wip sheet */
        for (int i = 0; i < message.length; i++)
        {
            //To get the only  : WIP Report with subject
			if ( message[i].getSubject() != null && message[i].getSubject().trim().length() > 0
                    && ( message[i].getSubject().startsWith( subject ) || message[i].getSubject().endsWith( subject ) || message[i].getSubject().indexOf(subject) != -1  ) )
            {
                Address address[] = message[i].getFrom();

                for( int j = 0; j < address.length ; j++ )
                {
                    //System.out.println( "From  :=  " + address[j].toString() );
                    //to get the only from address
                    if( address[j].toString() != null && address[j].toString().indexOf( FROM_ADDRESS) != -1 )
                    {
                        log( "From  :=  " + address[j].toString() );

                        Object obj = message[i].getContent();

                        if ( wipMessage == null )
                        {
                            if ( message[i].getDisposition() != null && ( message[i].getDisposition().equals( Message.ATTACHMENT ) || message[i].getDisposition().equals( Message.INLINE ) ) && message[i].getFileName() != null )
                            {
                                 wipMessage = message[i];
                            }
                            else
                            {
                                if (obj instanceof Multipart )
                                {
                                   mp = (Multipart) obj;

                                    for ( int m = 0; m < mp.getCount(); m++ )
                                    {
                                        part = mp.getBodyPart(m);

                                        if ( ( part.getDisposition() != null ) && ( part.getDisposition().equals( Part.ATTACHMENT ) || part.getDisposition().equals( Part.INLINE ))  )
                                        {
                                            wipMessage = message[i];
                                            break;
                                        }
                                        else if ( part.getFileName() != null )
                                        {
                                            wipMessage = message[i];
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            java.util.Date date1 = wipMessage.getSentDate();
                            java.util.Date date2 = null;

                            if ( message[i].getDisposition() != null && ( message[i].getDisposition().equals( Message.ATTACHMENT ) || message[i].getDisposition().equals( Message.INLINE ) ) && message[i].getFileName() != null )
                            {
                                 date2 = message[i].getSentDate();
                            }
                            else
                            {
                                if (obj instanceof Multipart )
                                {
                                   mp = (Multipart) obj;

                                    for ( int m = 0; m < mp.getCount(); m++ )
                                    {
                                        part = mp.getBodyPart(m);

                                        if ( ( part.getDisposition() != null ) && ( part.getDisposition().equals( Part.ATTACHMENT ) || part.getDisposition().equals( Part.INLINE ))  )
                                        {
                                            date2 = message[i].getSentDate();
                                            break;
                                        }
                                        else if ( part.getFileName() != null )
                                        {
                                            date2 = message[i].getSentDate();
                                            break;
                                        }
                                    }
                                }
                            }

                            if (date1 != null && date2 != null)
                            {
                                if (date2.compareTo(date1) > 0)
                                {
                                    wipMessage = message[i];
                                }
                            }
                        }
                    }
                }
            }
        }

        // To process the Message and download the files
        if ( wipMessage != null )
        {
            //System.out.println( "From ffsdfasfasf  :=  " + wipMessage.getFrom()[0].toString() );
            downLoadMessage( m_adaptor_id, wipMessage, wipMessage.getSentDate(), subject, outputDir, fileType, appendFileName );
            wipMessage = null;
        }
        else
        {
             log("\n\n****The Requested File was not found in INBOX***\n");
             System.out.println("\n\n****The Requested File was not found in INBOX***\n");
        }
    }

    public void downLoadMessage( int m_adaptor_id , Message message, Date sentDate, String subject , String outputDir, String fileType, String appendFileName) throws Exception
    {
        if ( message == null )
        {
            return;
        }

        Multipart mp        = null;
        Part part           = null;
        String disposition  = null;
        InputStream inputStream = null;

        String fileName     = null;
        log("Processing  Message for "+ subject + " .......");
        System.out.println("Processing  Message for "+ subject + " .......");

        try
        {
            Object obj = message.getContent();

            if (obj instanceof Multipart )
            {
                mp = (Multipart) obj;

                for ( int i = 0; i < mp.getCount(); i++ )
                {
                    part = mp.getBodyPart(i);

                    disposition = part.getDisposition();

                    //taking the wip attachmentS
                    if ( ( disposition != null ) && ( disposition.equals( Part.ATTACHMENT ) || disposition.equals( Part.INLINE ))  )
                    {
                        if ( part.getFileName() != null && part.getFileName().toUpperCase().indexOf(fileType.toUpperCase()) != -1 )
                        {
                            fileName =  part.getFileName().substring( 0 , part.getFileName().lastIndexOf(".") );
                            //System.out.println("fileName = " + fileName);

                            inputStream = part.getInputStream();

                            if ( fileName != null && !fileName.toUpperCase().startsWith("CONEXANT") && fileName.toUpperCase().indexOf("STARTS PLAN") == -1
                                    && fileName.toUpperCase().startsWith("IKANOS REPORT") && fileName.toUpperCase().indexOf("ATP") != -1 )
                            {
                                fileName = fileName.replaceAll("-", "_").toUpperCase();
                                                                                                
                                if ( m_adaptor_id > 0 )
                                {
                                    AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , fileName, fileType, StringUtils.formatDateToString( sentDate, "MM/dd/yyyy HH:mm:ss") ) ;
                                }

                                if ( appendFileName != null )
                                {
                                    fileName = appendFileName +"_" + fileName;
                                }

                                log("\tDownloding "+subject+"................. ");
                                System.out.println("\tDownloding "+subject+"................. ");

                                AdaptorUtils.saveAsBinaryFile( new BufferedInputStream(inputStream), outputDir, fileName, fileType, true /* append time stamp */);
                                fileName = null;
                                System.out.println("Done.\n"  );
                            }
                        }
                    }
                } //FOR LOOP
            }//IF FOR CHECKING ONLY MULTI PART

        }
        catch( Exception e)
        {
            System.out.println("EXception Occcuered while Proceess and downloading the Messge:" + e );
            e.printStackTrace();
            throw e;
        }
        finally
        {
            if ( inputStream != null )
            {
                try
                {
                    inputStream.close();
                    inputStream = null;
                }
                catch (IOException e)
                {
                }
            }
        }
    }
    private void log(String message)
    {
        if (message == null) return;

        if (m_adaptorLogger != null)
        {
            synchronized (m_adaptorLogger)
            {
                m_adaptorLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
}
